package com.mini.demos.webgame.codec;

import java.nio.charset.CharacterCodingException;
import java.util.logging.Logger;

import org.apache.mina.core.buffer.IoBuffer;

import com.mini.demos.webgame.msg.AbstractGameMsg;
import com.mini.demos.webgame.msg.MsgHead;
import com.mini.demos.webgame.msg.RegMsg;
import com.mini.demos.webgame.util.CommandConstants;
import com.mini.demos.webgame.util.Constants;

public class RegDecoder extends AbstractDecoder {
	private Logger log = Logger.getLogger("RegDecoder");

	@Override
	public AbstractGameMsg decodeBody(IoBuffer buffer, MsgHead head) {
		String regBody = "";
		try{
			regBody = buffer.getString(Constants.charset.newDecoder());
		}catch(CharacterCodingException cce){
			int bodyLength = head.getTotalLength()-Constants.HEAD_LEN;
			byte[] bodys = new byte[bodyLength];
			buffer.get(bodys);
			regBody = new String(bodys);
			
		}
		log.info("regBody:"+regBody);
		RegMsg msg = new RegMsg();
		msg.setHead(head);
		msg.setUserName(regBody.split(CommandConstants.COMMAND_SPLIT)[0]);
		msg.setUserPwd(regBody.split(CommandConstants.COMMAND_SPLIT)[1]);
		msg.setNickName(regBody.split(CommandConstants.COMMAND_SPLIT)[2]);
		return msg;
	}

	@Override
	public boolean isLegalCommand(int commandId) {
		if(commandId == CommandConstants.REG){
			return true;
		}
		return false;
	}

}
